package org.swift.commons.deployer.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PropertyUtils {

	private static Properties props = null;

	private final static Log log = LogFactory.getLog(PropertyUtils.class);

	public static String getProperty(String key) {
		return props.getProperty(key);
	}
	
	public static Properties getAllProperties() {
		return (Properties) props.clone();
	}
	
	public static void loadProps(ClassLoader classloader) {		
		props = new Properties();
		try {
			URL propUrl = classloader.getResource("mashup.properties");								
			if (propUrl == null) throw new NullPointerException("could not load mashup.properties");
			props.load( replacePlaceholders(propUrl.openStream()) );			
		} catch (IOException e) {
			log.warn("Error loading mashup.properties", e);
		}
	}

	public static InputStream replacePlaceholders(InputStream input) 
		throws IOException
	{
		StringBuffer outBuffer = new StringBuffer();
		InputStreamReader isr = new InputStreamReader(input);
		BufferedReader bufferedReader = new BufferedReader(isr);
		String currentLine = null;
		String currentPlaceHolder = null;
		int placeholderStartIndex = -1;
		while((currentLine = bufferedReader.readLine()) != null)
		{
			while((placeholderStartIndex = 
				currentLine.indexOf("${", placeholderStartIndex + 1)) != -1)
			{
				currentPlaceHolder = currentLine.substring(
						placeholderStartIndex, 
						currentLine.indexOf("}", placeholderStartIndex) + 1);
				if (System.getProperty(currentPlaceHolder.substring(2, 
						currentPlaceHolder.length() - 1)) == null) {					
					throw new NullPointerException("System Property not found: " + currentPlaceHolder);
				}
				currentLine = currentLine.replaceAll(
						Pattern.quote(currentPlaceHolder), 
						System.getProperty(currentPlaceHolder.substring(2, 
								currentPlaceHolder.length() - 1)));
			}
	
			outBuffer.append(currentLine).append('\n');
			placeholderStartIndex = -1;
		}

		byte[] bytes = outBuffer.toString().getBytes();
		return new ByteArrayInputStream(bytes);
	}
}
